package com.ymdx.util.tool;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.Collection;

/**
 * Created by yangliwei on 2017/8/14.
 * 复制相同类属性， notNull 为true 忽略空值  以及空字符串 ""
 */
public class BeanCopyUtil {
    public static void copyProperties(Object src, Object tar, Boolean notNull) {
        if (notNull) {
            BeanUtils.copyProperties(src, tar, excludes(src));
        } else {
            BeanUtils.copyProperties(src, tar);
        }
    }

    private static String[] excludes(Object source) {
        Collection<String> excludes = new ArrayList<>();
        BeanWrapper src = new BeanWrapperImpl(source);
        PropertyDescriptor[] propertyDescriptors = src.getPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            String propName = propertyDescriptor.getName();
            if (propertyDescriptor.getReadMethod() != null ) {
                if (src.getPropertyValue(propName) == null || StringUtils.isBlank(src.getPropertyValue(propName).toString())) {
                    excludes.add(propName);
                }

            } else {
                excludes.add(propName);
            }
        }
        String[] result = new String[excludes.size()];
        return excludes.toArray(result);
    }
}